<template>
  <div class="card" style="margin-bottom: 5px">
    <el-input clearable @clear="load" style="width: 300px;margin-right: 5px" v-model="data.keyword" placeholder="请输入收件人名称" :prefix-icon="Search"></el-input>
    <el-button type="primary" @click="load">查 询</el-button>
    <el-button @click="reset">重 置</el-button>
  </div>
  <div v-if="data.user.role === 'ADMIN'" class="card" style="margin-bottom: 5px; display: flex">
    <el-button type="primary" @click="handleAdd">添加包裹</el-button>
    <el-upload
        style="display: inline-block; margin:0 10px"
        action="http://localhost:8080/package/import"
        :show-file-list="false"
        :on-success="handleImportSuccess"
    >
      <el-button type="success">导入</el-button>
    </el-upload>
    <el-button type="info" @click="exportData">导出</el-button>
    <el-button type="danger" @click="deleteBatch">批量删除</el-button>
  </div>

  <div class="card" style="margin-bottom: 5px">
    <el-skeleton
        v-if="loading"
        :rows="6"
        animated    style="padding: 15px"
    />
    <el-table
        v-else
        v-loading="loading"
        element-loading-text="拼命加载中..."
        :data="data.tableData"
        style="width: 100%;"
        :max-height="600"
        @selection-change="handleSelectionChange"
        stripe
        border
        highlight-current-row
        :row-style="{ height: '55px' }"
        :header-cell-style="{
          backgroundColor: '#f5f7fa',
          color: '#606266',
          fontWeight: 600,
          fontSize: '14px'
        }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="缩略图" width="80">
        <template #default="scope">
          <el-image
              v-if="scope.row.thumbnail"
              :src="scope.row.thumbnail"
              :preview-src-list="[scope.row.thumbnail]"
              :initial-index="0"
              preview-teleported
              hide-on-click-modal
              fit="cover"      style="width: 45px; height: 45px; border-radius: 4px;"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="trackingNumber" label="快递单号" width="140" show-overflow-tooltip />
      <el-table-column prop="packageName" label="包裹名称" />
      <el-table-column prop="senderName" label="寄件人姓名" />
      <el-table-column prop="recipientName" label="收件人姓名" />
      <el-table-column prop="recipientPhone" label="收件人电话" />
      <el-table-column prop="recipientAddress" label="收件人地址" />
      <el-table-column prop="shippingTime" label="发货时间" />
      <el-table-column prop="courier" label="快递公司" />
      <el-table-column prop="state" label="包裹状态" width="100">
        <template #default="{row}">
          <el-tag :type="getStateType(row.state)" effect="plain">
            {{ row.state }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="data.state === '待签收'" prop="pickupCode" label="取件码" />
      <el-table-column v-if="data.state === '待签收'" prop="inboundTime" label="入库时间" />
      <el-table-column v-if="data.user.role === 'ADMIN'" label="操作" width="120">
        <template #default="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button type="primary" icon="Edit" circle size="small" @click="handleEdit(scope.row)"/>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button type="danger" icon="Delete" circle size="small" @click="del(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="card" style="margin-bottom: 5px">
    <el-pagination
        v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 15]"
        :total="data.total"
        @current-change="load"
        @size-change="load"
    />

    <el-dialog v-model="data.FormVisible" title="包裹信息" width="800" style="--el-dialog-margin-top:5vh" destroy-on-close>
      <el-form ref="fromRef" :model="data.form" :rules="data.rules" label-width="100px" style="padding: 20px 30px 10px 0;">
        <el-form-item prop="thumbnail">
          <el-upload
              action="http://localhost:8080/files/upload"
              :headers="{ token: data.user.token }"
              :on-success="handleFileSuccess"
              list-type="picture-card"
              :limit="1"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="trackingNumber" label="快递单号" >
          <el-input v-model="data.form.trackingNumber" placeholder="请输入快递单号" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="packageName" label="包裹名称">
          <el-input v-model="data.form.packageName" placeholder="请输入包裹名称" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="senderName" label="寄件人姓名">
          <el-input v-model="data.form.senderName" placeholder="请输入寄件人姓名" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="senderPhone" label="寄件人电话">
          <el-input v-model="data.form.senderPhone" placeholder="请输入寄件人电话" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="senderAddress" label="寄件人地址">
          <el-input v-model="data.form.senderAddress" placeholder="请输入寄件人地址" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="recipientName" label="收件人姓名">
          <el-input v-model="data.form.recipientName" placeholder="请输入收件人姓名" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="recipientPhone" label="收件人电话">
          <el-input v-model="data.form.recipientPhone" placeholder="请输入收件人电话" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="recipientAddress" label="收件人地址">
          <el-input v-model="data.form.recipientAddress" placeholder="请输入收件人地址" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="courier" label="快递公司">
          <el-select v-model="data.form.courier" placeholder="请选择快递公司">
            <el-option
                v-for="item in ['顺丰速运', '邮政快递', '极兔速递', '圆通速递', '中通快递', '申通快递', '韵达快递', '天天快递']"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="shippingTime" label="发货时间">
          <el-date-picker
              v-model="data.form.shippingTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择发货日期"
              :default-value="new Date()"
          />
        </el-form-item>
        <el-form-item label="包裹状态">
          <el-input
              v-model="data.form.state"
              placeholder="未发货"
              style="--el-input-readonly-bg-color: #f5f7fa;"
          />
        </el-form-item>
        <el-form-item label="包裹备注">
          <el-input v-model="data.form.packageIntroduction" placeholder="备注" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.FormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

const emit = defineEmits(['updateUser'])

const route = useRoute()
const props = defineProps({
  packageState: {
    type: String,
    default: ''
  }
});

const data = reactive({
  user: JSON.parse(localStorage.getItem("code_user") || '{}'),
  keyword: null,
  state: props.packageState,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  FormVisible: false,
  form: {},
  rules: {
    trackingNumber: [
      { required: true, message: '请输入快递单号', trigger: 'blur' },
      { min: 10, max: 10, message: '快递单号长度为10位', trigger: 'blur' }
    ],
    packageName: [
      { required: true, message: '请输入包裹名称', trigger: 'blur' },
    ],
    senderName: [
      { required: true, message: '请输入寄件人姓名', trigger: 'blur' },
    ],
    senderPhone: [
      { required: true, message: '请输入寄件人电话', trigger: 'blur' },
    ],
    senderAddress: [
      { required: true, message: '请输入寄件人地址', trigger: 'blur' },
    ],
    recipientName: [
      { required: true, message: '请输入收件人姓名', trigger: 'blur' },
    ],
    recipientPhone: [
      { required: true, message: '请输入收件人电话', trigger: 'blur' },
    ],
    recipientAddress: [
      { required: true, message: '请输入收件人地址', trigger: 'blur' },
    ],
    courier: [
      { required: true, message: '请选择快递公司', trigger: 'change' }
    ],
    shippingTime: [
      { required: true, message: '请选择发货日期', trigger: 'change' }
    ]
  },
  rows: [],
  ids: [],
});

const fromRef = ref()

const loading = ref()

const getStateType = (state) => {
  const typeMap = {
    '未发货': 'info',
    '已发货': 'primary',
    '待签收': 'warning',
    '已签收': 'success',
    '已退回': 'danger'
  }
  return typeMap[state] || 'info'
}

const load = async () => {
  loading.value = true
  const startTime = Date.now() // 记录开始时间
  // 构造查询参数
  const params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    keyword: data.keyword,
    state: data.state
  }

  if (data.user.role === 'USER') {
    params.senderName = data.user.name
    params.recipientName = data.user.name
  }
  try {
    const res = await request.get('/package/selectPage', { params })

    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg)
    }
  } catch (e) {
    ElMessage.error('数据加载失败')
  } finally {
    // 计算剩余需要等待的时间
    const elapsed = Date.now() - startTime
    const remaining = Math.max(500 - elapsed, 0)
    setTimeout(() => {
      loading.value = false
    }, remaining)
  }
};

const reset = () => {
  data.keyword = null;
  load();
};

const handleAdd = () => {
  data.FormVisible = true;
  data.form = {
    shippingTime: new Date().toISOString().split('T')[0],
    state: '未发货'
  };
};

const add = () => {
  fromRef.value.validate((valid) => {
    if (valid) {
      request.post('/package/add', data.form).then(res => {
        if (res.code === '200') {
          data.FormVisible = false;
          ElMessage.success('新增成功');
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
};

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.FormVisible = true;
};

const update = () => {
  fromRef.value.validate((valid) => {
    if (valid) {
      request.put('/package/update', data.form).then(res => {
        if (res.code === '200') {
          data.FormVisible = false;
          ElMessage.success('修改成功');
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
};

const save = () => {
  data.form.id ? update() : add();
};

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，确定要删除吗？', '提示', { type: 'warning' }).then(res => {
    request.delete('/package/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {});
};

const handleSelectionChange = (rows) => {
  data.rows = rows;
  data.ids = data.rows.map(v => v.id);
};

const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  ElMessageBox.confirm('删除后无法恢复，确定要删除吗？', '提示', { type: 'warning' }).then(res => {
    request.delete('/package/deleteBatch', { data: data.rows }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {});
};

const exportData = () => {
  let idsStr = data.ids.join(",");
  let url = `http://localhost:8080/package/export?keyword=${data.keyword === null ? '' : data.keyword}` +
      `&state=${data.state}` +
      `&ids=${idsStr}` +
      `&token=${data.user.token}`;
  window.open(url);
};

const handleImportSuccess = (res) => {
  if (res.code === '200') {
    ElMessage.success('导入数据成功');
    load();
  } else {
    ElMessage.error(res.msg);
  }
};

const handleFileSuccess = (res) => {
  data.form.thumbnail = res.data
}

// 路由监听
watch(
    () => route.path,
    (newPath) => {
      const stateRoutes = [
        '/manager/express/allPackage',
        '/manager/express/unshipped',
        '/manager/express/shipped',
        '/manager/express/unsigned',
        '/manager/express/signed',
        '/manager/express/returned'
      ]
      if (stateRoutes.includes(newPath)) {
        data.state = props.packageState
        load()
      }
    },
    { immediate: true }
)


</script>

<style scoped>

.el-skeleton__item {
  background: rgba(240, 242, 245, 0.5);
  margin: 10px 0;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

/* 图片加载失败样式 */
.image-error {
  width: 45px;
  height: 45px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  border-radius: 4px;
}

/* 表格悬停效果 */
.el-table__body tr:hover>td {
  background-color: #f5f7fa !important;
}

/* 分页样式 */
.el-pagination {
  padding: 15px 0;
  justify-content: flex-end;
}

/* 表单弹窗样式 */
:deep(.el-dialog__body){
  padding: 20px 30px;
}

/* 快递公司选择器 */
.el-select {
  width: 100%;
}

/* 日期选择器 */
.el-date-editor {
  width: 100%;
}
</style>